<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\model\Address as AddressModel;
use think\Db;

class Address extends Frontend
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        $address = Db::name('address')->where(['uid' => 1])->select();
        $this->assign('address', $address);
        $this->assign('title', '收货地址管理');
        return $this->view->fetch();
    }

    public function select()
    {

    }

    public function add()
    {
        if(request()->isAjax()) {
            $uid = 1;//$this->auth->id;
            $addressModel = new AddressModel;
            $data = input();
            if(isset($data['is_default'])) {
                $data['is_default'] = 1;
            }
            if(isset($data['is_default'])) {
                Db::name('address')->where(['uid' => $uid])->update([
                    'is_default' => 0
                ]);
            }
            $data['uid'] = $uid;
            $result = $addressModel->validate()->save($data);
            if(false === $result){
                $this->error($addressModel->getError());
            }else{
                $this->success('添加成功', url('address/index'));
            }
        }
        $this->assign('title', '添加收货地址');
        return $this->view->fetch();
    }

    public function edit($id)
    {
        if(request()->isAjax()) {
            $uid = $this->auth->id;
            $addressModel = AddressModel::get($id);
            $data = input();
            if(isset($data['is_default'])) {
                $data['is_default'] = 1;
            }else{
                $data['is_default'] = 0;
            }
            if(isset($data['is_default'])) {
                Db::name('address')->where(['uid' => $uid])->update([
                    'is_default' => 0
                ]);
            }
            $result = $addressModel->validate()->save($data);
            if(false === $result){
                $this->error($addressModel->getError());
            }else{
                $this->success('更新成功', url('address/index'));
            }
        }
        $address = Db::name('address')->where(['id' => $id])->find();
        $this->assign('address', $address);
        $this->assign('title', '编辑收货地址');
        return $this->view->fetch();
    }
}
